import { createRouter, createWebHistory } from 'vue-router'
import loginView from '@/views/login/index.vue'

import searchView from '@/views/home/serach.vue'
import homeView from '@/views/home/home.vue'
import indexView from '@/views/home/children/index.vue'
import claView from '@/views/home/children/cla.vue'
import cartView from '@/views/home/children/cart.vue'
import myView from '@/views/home/children/my.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    { path: '/', redirect: '/home/index' },
    // 登入主页面
    { path: '/login', component: loginView },
    // 搜索主页面
    { path: '/search', component: searchView },
    {
      path: '/home', component: homeView, children:
        [
          // 二级,首页 分类 购物车 我的
          { path: 'index', component: indexView },
          { path: 'cla', component: claView },
          { path: 'cart', component: cartView },
          { path: 'my', component: myView },
        ]
    },
  ],
})

export default router
router.beforeEach((to, from, next) => {
  if (to.fullPath == '/home/cart' || to.fullPath == '/home/my') {
    let token = localStorage.getItem('token')
    if (!token) {
      next('/login')
    }
    else {
      next()
    }
  }
  else {
    next()
  }
})